<!--  -->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row :gutter = "20">
                <el-col :span = "8">
                    <el-input placeholder="请输入内容"  class="input-with-select" size = "large"
                     v-model = "query"
                     clearable
                     @clear = "getUserList"
                    >
                    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                </el-input>
                </el-col>
                <el-col :span = "4">
                    <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
                    <!-- 添加用户的dialog -->
                    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" @close = "close">
                    <el-form :model="form" :rules="rules" ref="ruleForm">
                        <el-form-item label="用户名" :label-width="formLabelWidth" prop = "username">
                            <el-input v-model="form.username" autocomplete="off" ></el-input>
                        </el-form-item>
                        <el-form-item label="密码" :label-width="formLabelWidth" prop = "password">
                            <el-input v-model="form.password" autocomplete="off" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" :label-width="formLabelWidth" prop = "email">
                            <el-input v-model="form.email" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" :label-width="formLabelWidth"  prop = "mobile">
                            <el-input v-model="form.mobile" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取 消</el-button>
                            <el-button type="primary" @click="addUser">确 定</el-button>
                        </div>
                    </el-dialog>
                    <!-- 修改用户的对话框 -->
                    <el-dialog
                        title="修改信息"
                        :visible.sync="editDialogVisible"
                        width="50%"
                        @close = "closeEdit"
                        >
                        <el-form :model="editForm" :rules="editRules" ref="editRef">
                            <el-form-item label="用户名" :label-width="formLabelWidth">
                                <el-input v-model="editForm.username" autocomplete="off" disabled></el-input >
                            </el-form-item>
                            <el-form-item label="邮箱" :label-width="formLabelWidth" prop = "email">
                                <el-input v-model="editForm.email" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" :label-width="formLabelWidth" prop = "mobile">
                                <el-input v-model="editForm.mobile" autocomplete="off" ></el-input>
                            </el-form-item>
                            
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="editDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="editUserInfo">确 定</el-button>
                        </span>
                    </el-dialog>
                </el-col>
            </el-row>
            <!-- 用户列表 -->
            <el-table
            :data="userList" border stripe
            style="width: 100%">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column 
                    prop="username"
                    label="姓名"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="mobile"
                    label="电话"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="role_name"
                    label="角色"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="mg_state"
                    label="状态"
                    width="180">
                    <template slot-scope="scope">
                        <el-switch @change = "changeState(scope.row.mg_state,scope.row.id)"
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="180">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                       <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)"></el-button>
                       <!-- 删除按钮 -->
                       <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
                       <!-- 分配角色按钮 -->
                       <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="block">
                <el-pagination
                :page-sizes="[2, 5, 8, 10]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-size="pagesize"
                :current-page="pagenum"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>

            <!-- 分配角色的对话框 -->
                <el-dialog
                title="分配角色"
                :visible.sync="userDialog"
                width="30%"
                :before-close="closeUserDialog"
                >
                <div>
                    <p>当前用户:{{userInfo.username}}</p>
                    <p>当前角色:{{userInfo.role_name}}</p>
                    <p>
                        分配新的角色:
                        <el-select v-model="selectedRoleId" clearable placeholder="请选择">
                            <el-option
                            v-for="item in rolesList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                            </el-option>
                        </el-select>
                        
                    </p>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="userDialog = false">取 消</el-button>
                    <el-button type="primary" @click="saveInfo">确 定</el-button>
                </span>
            </el-dialog>

        </el-card>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
    // 自定义验证邮箱规则
     var checkEmail = (rule, value, cb) => {
     const regEmail = /^\w+@\w+(\.\w+)+$/
     if (regEmail.test(value)) {
      return cb()
     }
     //返回一个错误提示
     cb(new Error('请输入合法的邮箱'))
    }
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
            return cb()
        }
        //返回一个错误提示
        cb(new Error('请输入合法的手机号码'))
    }
return {
    userList:[],
    total:0,
    value:true,
    pagenum:1,
    pagesize:5,
    query:"",
    dialogFormVisible:false,
    form: {
        username: '',
        password: '',
        email: '',
        mobile: '',
    }, 
    formLabelWidth: '120px',
    rules:{
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
          ],
           password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator:checkEmail,trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator:checkMobile,trigger: 'blur' }
          ],
    },
    editDialogVisible:false,
    editForm:"",
    editRules:{
        email:[
            { required: true, message: '请输入新的邮箱', trigger: 'blur' },
            { validator:checkEmail,trigger: 'blur' }
        ],
        mobile: [
            { required: true, message: '请输入新的手机号码', trigger: 'blur' },
            { validator:checkMobile,trigger: 'blur' }
        ]
    },
    userDialog:false,
    userInfo:{},
    rolesList:[],
    selectedRoleId:""
  };
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    // 获取用户列表
    async getUserList(){
        const {data} = await this.$http({
            url:"users",
            params:{
                query:this.query,
                pagenum:this.pagenum,
                pagesize:this.pagesize
            }
        });
        if (data.meta.status == 200) {
            this.userList = data.data.users;
            this.total = data.data.total;
        }
        // console.log(data);
    },

    handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
        this.pagesize = val;
        this.getUserList();
      },

    handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.pagenum = val;
        this.getUserList();
    },
    async changeState(value,id){
        // console.log(value,id);

        const { data } = await this.$http.put(`users/${id}/state/${value}`)
        console.log(data);
        if (data.meta.status == 200) {
             this.$message({
                type: 'success',
                message: '设置状态成功!'
          });
        }
    },
    close(){
        this.$refs.ruleForm.resetFields()
    },
    closeEdit(){
        this.$refs.editRef.resetFields()
    },
    addUser(){
        this.$refs.ruleForm.validate(async valid =>{
            if( !valid ) return
            // 校验成功,发送添加用户请求
            const {username,password,email,mobile} = this.form;
            const {data}  = await this.$http({
                url:"users",
                method:"POSt",
                data:{
                    username,
                    password,
                    email,
                    mobile
                }
            });
            // console.log(data)
            if (data.meta.status = 200) {
                this.$message({
                     type: 'success',
                     message: '添加用户成功!'
                });
                this.dialogFormVisible = false;
                this.getUserList()
            }
        })
    },
    // 编辑用户
    async edit(id){
        // console.log(id)
        const { data } = await this.$http.get(`users/${id}`);
        // console.log(data);
        this.editForm = data.data;
        console.log(this.editForm);
        this.editDialogVisible = true;
    },
    // 修改用户信息并比较
    editUserInfo(){
        this.$refs.editRef.validate(async valid =>{
            if( !valid ) return
            // 校验成功,发送修改用户请求
            const {id,email,mobile} = this.editForm;
            const {data}  = await this.$http.put(`users/${id}`,{
                email,mobile
            });
           
            if (data.meta.status = 200) {
                this.$message({
                     type: 'success',
                     message: '更改信息成功!'
                });
                this.editDialogVisible = false;
                this.getUserList()
            }
        })
    },
    // 删除用户
    delUser(id){
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        const {data} = await this.$http.delete(`users/${id}`)
        // console.log(data);
          this.$message({
            type: 'success',
            message: '已成功删除!'
          });
          this.getUserList();
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    closeUserDialog(){
        this.$confirm('确认关闭？')
          .then(() => {
           this.userDialog = false;
          })
          .catch(()=>{})
    },
    async setRole(userInfo){
        this.userInfo = userInfo;

        const {data} = await this.$http.get("roles");
        if (data.meta.status !== 200) {
            return this.$message.error("获取失败");
        }
        this.rolesList = data.data;
        // console.log(this.rolesList)
        this.userDialog = true;
    },
    async saveInfo(){
        if (!this.selectedRoleId) {
            return this.$message.error("请选择要分配的角色")
        }
       const { data } = await this.$http.put(`users/${this.userInfo.id}/role`,{
            rid:this.selectedRoleId
        });
        console.log(data)
        if (data.meta.status !== 200) {
            return this.$message.error("更新角色失败");
        }else{
            this.$message.success("更新角色成功")
        }
        this.getUserList();
        this.userDialog = false;
    }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
     this.getUserList();
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.el-breadcrumb{
    margin-bottom: 15px;
    font-size: 14px;
}
.el-table{
    margin-top: 15px;
}
.el-pagination{
    margin-top: 15px;
}
</style>